package com.yungu.swift.order.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.api.ApiPageParam;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.common.service.CommonEvaluateCountService;
import com.yungu.swift.common.service.CommonSensitiveWordService;
import com.yungu.swift.common.service.CommonStarCountService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.dao.OrderEvaluateMapper;
import com.yungu.swift.order.helper.OrderHelper;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.model.dto.OrderEvaluateDto;
import com.yungu.swift.order.service.OrderEvaluateService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

import static com.yungu.swift.order.model.enums.OrderErrorEnum.ERR_CODE_EVALUATE_SENSITIVEWORD;


/**
 * OrderEvaluateServiceImpl
 **/
@Service
public class OrderEvaluateServiceImpl extends BaseServiceImpl<OrderEvaluateDto> implements OrderEvaluateService {

    @Autowired
    private OrderEvaluateMapper orderEvaluateMapper;
    @Autowired
    private OrderService orderService;

    @Reference
    private PassengerService passengerService;
    @Reference
    private DriverService driverService;
    @Reference
    private CommonStarCountService commonStarCountService;
    @Reference
    private CommonEvaluateCountService evaluateCountService;
    @Reference
    private CommonSensitiveWordService commonSensitiveWordService;

    @Override
    protected IMapper<OrderEvaluateDto> getMapper() {
        return orderEvaluateMapper;
    }

    @Override
    public ResponseData<PageList<OrderEvaluateDto>> getListOfEvaluate(String uuid, ApiPageParam apiPageParam) {
        Map<String, Object> map = MapUtils.build(4);
        map.put("toUuid", uuid);
        map.put("beforeDate", 1);
        PageBounds pageBounds = new PageBounds(apiPageParam.getNowPage(), apiPageParam.getPageSize());
        return ResponseData.buildSuccessResponse(orderEvaluateMapper.queryPage(map, pageBounds));
    }

    @Override
    public ResponseData<String> addComment(String userUuid, String orderUuid, String comment, String commentId, Double score) {
        ResponseData<String> sensitiveWordsCheck = commonSensitiveWordService.checkContainSensitiveWords(comment, 2);
        if (!sensitiveWordsCheck.isSuccess()) {
            return ResponseData.buildErrorResponse(ERR_CODE_EVALUATE_SENSITIVEWORD.getCode(), ERR_CODE_EVALUATE_SENSITIVEWORD.getMsg(), sensitiveWordsCheck.getData());
        }
        OrderDto orderDto = orderService.get(orderUuid).getData();
        if (orderDto == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到订单信息");
        }
        /**
         * 跨城分支
         */
        if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_POOL || orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
            if (OrderConstant.ORDER_JOIN_STATUS_COMMENTED == orderDto.getJoinStatus()) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "订单已评价");
            }
            if (orderDto.getJoinStatus() < OrderConstant.ORDER_JOIN_STATUS_WAIT_START) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未指派订单无法评价");
            }
        } else {
            if (OrderConstant.ORDER_STATUS_COMMENTED.equals(orderDto.getJoinStatus())) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "订单已评价");
            }
            if (!OrderConstant.ORDER_STATUS_COMPLETE.equals(orderDto.getSubStatus())) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未支付的订单不能评价");
            }
        }
        if (!OrderConstant.ORDER_STATUS_COMPLETE.equals(orderDto.getSubStatus())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未支付的订单不能评价");
        }
        PassengerDto passengerDto = passengerService.get(userUuid).getData();
        if (passengerDto == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到乘客信息");
        }

        if (orderDto != null && passengerDto != null) {
            String driverUuid = orderDto.getActualDriverUuid();
            //插入评价记录到数据库
            OrderEvaluateDto orderEvaluateDto = new OrderEvaluateDto();
            orderEvaluateDto.setUuid(StringUtils.buildUUID());
            orderEvaluateDto.setOrderUuid(orderUuid);
            orderEvaluateDto.setMobile(passengerDto.getMobile());
            orderEvaluateDto.setName(passengerDto.getNickname());
            orderEvaluateDto.setFromUuid(userUuid);
            orderEvaluateDto.setToUuid(driverUuid);
            orderEvaluateDto.setScore(score);
            orderEvaluateDto.setContent(comment);
            orderEvaluateDto.setEvaluateTag(commentId);
            orderEvaluateDto.setCreateOn(new Date());
            orderEvaluateMapper.add(orderEvaluateDto);

            //更改订单表，子状态改为完成对车主的评价
            OrderDto newOrderDto = new OrderDto();
            newOrderDto.setUuid(orderUuid);
            newOrderDto.setSubStatus(OrderConstant.ORDER_STATUS_COMMENTED);
            newOrderDto.setUpdateOn(new Date());
            /**
             * 跨城分支
             */
            if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_POOL || orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
                newOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_COMMENTED);
            }
            OrderHelper.saveOrUpdate(newOrderDto);
            //更新司机的评分
            Map<String, Object> map = MapUtils.build();
            map.put("uuid", driverUuid);
            //获取司机的平均评分
            Double averageScore = orderEvaluateMapper.findAverageScoreByTime(map);
            BigDecimal newScore = BigDecimal.valueOf(averageScore).setScale(1, BigDecimal.ROUND_HALF_UP);
            driverService.updDriverScore(driverUuid, newScore.doubleValue());
            //更新评价标签统计
            evaluateCountService.updEvaluateCount(driverUuid, commentId);
            //更新星数统计
            commonStarCountService.updStarCount(driverUuid, score);
            return ResponseData.buildSuccessResponse(null);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "保存评价信息失败");
    }

    @Override
    public ResponseData<Double> findAverageScoreByLength(String uuid, Integer start, Integer length) {
        Map<String, Object> map = MapUtils.build(5);
        map.put("uuid", uuid);
        map.put("start", start);
        map.put("length", length);
        Double score = Optional.ofNullable(orderEvaluateMapper.findAverageScoreByTime(map)).orElse(0.0D);
//        BigDecimal bd = BigDecimal.valueOf(score).setScale(1, BigDecimal.ROUND_HALF_UP);
        BigDecimal bd = BigDecimal.valueOf(score).setScale(2, BigDecimal.ROUND_HALF_UP);
        return ResponseData.buildSuccessResponse(bd.doubleValue());
    }
}
